package com.kobeliu.component;

import com.kobeliu.strategy.ShardingDBConfig;
import com.kobeliu.util.CommonUtil;
import org.springframework.stereotype.Component;

@Component
public class ShortLinkComponent {

    /**
     * 生成短链码
     * @param param
     * @return
     */
    public String createShortLinkCode(String param){

       long murmurHash = CommonUtil.murmurHash32(param);

       //进制转换
        String code = encodeToBase62(murmurHash);

        //组装
        //懒得改了默认都是 0 1 a 三库三表
        String shortLinkCode = ShardingDBConfig.getRandomDBPrefix() + code + ShardingDBConfig.getRandomDBPrefix();

        return shortLinkCode;
    }

    /**
     * 10进制转62进制
     * @param murmurHash
     * @return
     */
    private String encodeToBase62(long murmurHash) {

        //StringBuffer线程安全
        StringBuffer sb = new StringBuffer();
        do{
            int i = (int)murmurHash%62;
            sb.append(i);
            murmurHash/=62;
        }while (murmurHash>0);

        String value = sb.reverse().toString();
        return value;
    }

}
